<template>
  <div class="team-detail-page">
    <!-- 队伍详情卡片 -->
    <van-cell-group>
      <van-cell title="队伍名字" :value="teamInfo.teamName"/>
      <van-cell title="队长" :value="teamInfo.leaderUserName"/>
      <van-cell title="最大人数" :value="`${teamInfo.maxNum}人`"/>
      <van-cell title="当前队伍人数" :value="`${teamInfo.currentNum}人`"/>
      <van-cell title="队伍描述" :value="teamInfo.description"/>
      <van-cell title="截止时间" :value="teamInfo.expireTime"/>
      <van-cell title="当前成员">
        <template #value>
          <van-tag
              v-for="user in teamInfo.members"
              :key="user.id"
              type="primary"
              size="medium"
              style="margin-right: 8px"
          >
            {{ user.username }}
          </van-tag>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 修改按钮（仅队长可见） -->
    <div v-if="isLeader" class="action-buttons">
      <van-button type="primary" block @click="showEditDialog = true">
        修改队伍信息
      </van-button>
    </div>

    <!--    解散队伍-->
    <div v-if="isLeader" class="action-buttons">
      <van-button type="danger" block @click="handleDissolveTeam(teamInfo.teamName)">
        解散队伍
      </van-button>
      <!-- 解散队伍的确认弹窗 -->
      <van-dialog
          v-model:show="showDissolveConfirm"
          title="确认解散队伍"
          message="确定要解散队伍吗？"
          show-cancel-button
          @confirm="handleDissolveConfirm"
      />
    </div>


    <!-- 修改队伍信息的弹窗 -->
    <van-dialog
        v-model:show="showEditDialog"
        title="修改队伍信息"
        show-cancel-button
        @confirm="handleUpdateTeam"
    >
      <van-field
          v-model="editForm.teamName"
          label="队伍名字"
          placeholder="请输入队伍名字"
      />
      <van-field
          v-model="editForm.maxNum"
          label="最大人数"
          type="number"
          placeholder="请输入最大人数"
      />

      <!--      修改队伍描述-->
      <van-field
          v-model="editForm.description"
          label="队伍描述"
          placeholder="请输入队伍描述"
      />


      <!--    单选框是否加密-->
      <van-radio-group v-model="editForm.status" :rules="[{ required: true, message: '请选择是否加密' }]">
        <van-cell title="房间类型">
          <template #value>
            <van-radio name="0">公开</van-radio>
            <van-radio name="1">加密</van-radio>
          </template>
        </van-cell>
      </van-radio-group>

      <!--      当点击加密的时候出现输入密码框，否则不出现-->
      <div v-if="editForm.status === '1'">
        <van-field
            v-model="editForm.userPassword"
            label="密码"
            type="password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]"
        />
      </div>

      <!--      设置过期时间-->
      <div>
        过期时间
        <van-date-picker
            visible-option-num="1"
            v-model="currentDate"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
        />

        <!--      选择时间-->
        <van-time-picker
            visible-option-num="1"
            v-model="currentTime"
            title="选择时间"
            :columns-type="columnsType"
        />
      </div>


    </van-dialog>


  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {useRoute} from 'vue-router';
import {showToast} from 'vant';
import {deleteTeamApi, selectUserByTeamId, updateTeamApi} from "../apis/teamApi.js";
import {getUserByIdApi} from "../apis/userApi.js";
import {useUserStore} from "../store/userStore.js";
import dateTimeTransform from "../utils/DateUtil.js";
import teamQuery from "../pojo/teamQuery.js";
import router from "../router/index.js";

//日期选择器

const currentDate = ref(['2021', '01', '01']);
let minDate = new Date(2025, 1, 1)
let maxDate = new Date(2030, 5, 1)

const currentTime = ref(['12', '00', '00']);
const columnsType = ['hour', 'minute', 'second'];

// 获取路由参数
const route = useRoute();
const userStore = useUserStore()
const currentUserId = userStore.userInfo.id

// 队伍详情
const teamInfo = reactive({
  teamId: route.query.teamId,
  teamName: route.query.teamName,
  maxNum: route.query.maxNum,
  description: route.query.description,
  leaderId: route.query.leaderId,
  currentNum: 0,
  leaderUserName: '',
  members: [], // 当前加入队伍的用户列表
  status: 0,  //队伍状态
  userPassword: '',
  expireTime: route.query.expireTime,
})

console.log(teamInfo)


// 是否是队长
const isLeader = ref(false);

// 修改队伍信息的弹窗状态
const showEditDialog = ref(false);

// 修改表单数据
const editForm = reactive({
  teamName: '',
  maxNum: 0,
  description: '',
  status: 0,
  userPassword: '',
  expireTime: '',
});


// 获取队伍详情
onMounted(async () => {
  try {
    console.log(teamInfo.teamId)
    const resp = await selectUserByTeamId(teamInfo.teamId);
    console.log(resp)
    if (resp.data.code === 200) {
      teamInfo.members = resp.data.data
      teamInfo.currentNum = teamInfo.members.length

      if (teamInfo.leaderId == currentUserId)
        isLeader.value = true
      console.log(isLeader.value)

      // 初始化修改表单
      editForm.description = teamInfo.description
      editForm.teamId = teamInfo.teamId
      editForm.teamName = teamInfo.teamName
      editForm.maxNum = teamInfo.maxNum
      editForm.status = teamInfo.status
      editForm.userPassword = teamInfo.userPassword
      editForm.expireTime = teamInfo.expireTime


    } else {
      showToast('获取队伍详情失败');
    }

    //根据队长id获取队长名字
    const resp2 = await getUserByIdApi(teamInfo.leaderId)
    console.log(resp2)
    if (resp2.data.code === 200) {
      teamInfo.leaderUserName = resp2.data.data.username
    }

  } catch (error) {
    showToast('请求失败，请稍后重试');
    console.error('获取队伍详情失败：', error);
  }
});

// 修改队伍信息
const handleUpdateTeam = async () => {

  //根据表单创建也给teamQuery请求对象

  let query = new teamQuery()

  query.id = editForm.teamId
  query.teamName = editForm.teamName
  query.maxNum = editForm.maxNum
  query.description = editForm.description
  query.status = editForm.status


  // 拼接日期和时间
  query.expireTime = dateTimeTransform(currentDate, currentTime)
  console.log(
      "teamQuery:", query
  )
  if (editForm.status == 1)
    query.userPassword = editForm.userPassword
  else
    query.userPassword = null

  try {
    const resp = await updateTeamApi(query);
    console.log(resp)
    if (resp.data.code === 200) {
      showToast('修改成功');
      teamInfo.teamName = editForm.teamName;
      teamInfo.maxNum = editForm.maxNum;
    } else {
      showToast('修改失败');
    }
  } catch (error) {
    showToast('修改失败，请稍后重试');
    console.error('修改队伍信息失败：', error);
  }
};


async function handleDissolveTeam(teamName) {
  const result=await deleteTeamApi(teamName)
  console.log(result)
  if(result.data.code===200){
    showToast('解散成功');
    router.back('/teamList')
  }else{
    showToast('解散失败');
  }

}


</script>

<style scoped>
.team-detail-page {
  padding: 16px;
}

.action-buttons {
  margin-top: 24px;
}
</style>